package org.example.service;

import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.config.annotation.DubboService;
import org.example.User;
import org.example.UserRequest;
import org.example.UserService;
import org.example.bean.Store;

import java.util.HashMap;
import java.util.Map;

@DubboService
public class UserServiceImpl implements UserService {

    private static final Map<String, User> USER_MAP = new HashMap<>();
    private static boolean useSwitch = false;

    static {
        USER_MAP.put("123", User.newBuilder().setUid("123").setUsername("chenwj").build());
        USER_MAP.put("456", User.newBuilder().setUid("456").setUsername("zhang").build());
    }
    @Override
    public User getUser(UserRequest request) {
        String uid = request.getUid();
        System.out.println("服务端===用户(getUser)===收到远程调用 -> " + uid);
        User user = USER_MAP.get(uid);
        System.out.println("服务端===用户(getUser)===返回数据 -> " + user + "\n");
        return user;
    }

    @Override
    public StreamObserver<UserRequest> getUserStream(StreamObserver<User> responseObserver) {
        System.out.println("服务端===用户(getUserStream)===收到远程调用");
        return new StreamObserver<UserRequest>() {
            @Override
            public void onNext(UserRequest userRequest) {
                // 接收客户端发送过来的数据，然后返回数据给客户端
                System.out.print("服务端===用户(getUserStream)===onNext===接收客户端发送过来的数据 -> " + userRequest);
                while (true) {
                    if (useSwitch) {
                        User user = USER_MAP.get(userRequest.getUid());
                        System.out.print("服务端===用户(getUserStream)===onNext===获取用户数据并返回客户端 -> " + user);
                        responseObserver.onNext(user);
                        responseObserver.onCompleted();
                        return;
                    }
                }
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("服务端===用户(getUserStream)===Throwable -> " + throwable);
            }

            @Override
            public void onCompleted() {
                System.out.println("服务端===用户(getUserStream)===接收客户端发送过来的数据完毕\n");
                useSwitch = false;
            }
        };
    }

    public void openUserSwitch() {
        useSwitch = true;
    }
}
